package com.platform.modules.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import com.platform.common.config.PlatformConfig;
import com.platform.common.constant.AppConstants;
import com.platform.common.exception.BaseException;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.upload.config.UploadConfig;
import com.platform.common.upload.utils.BaseUtils;
import com.platform.common.upload.utils.OssUtils;
import com.platform.common.upload.vo.UploadAudioVo;
import com.platform.common.upload.vo.UploadFileVo;
import com.platform.common.upload.vo.UploadVideoVo;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.modules.chat.config.TencentConfig;
import com.platform.modules.chat.utils.ParseContent;
import com.platform.modules.chat.utils.TencentUtils;
import com.platform.modules.common.config.OssConfig;
import com.platform.modules.common.service.FileService;
import com.platform.modules.common.utils.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service("fileService")
public class FileServiceImpl implements FileService {

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private TencentConfig tencentConfig;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public UploadFileVo uploadFile(MultipartFile file) {
        String fileType = FileNameUtil.extName(file.getOriginalFilename());
        if ("webp".equalsIgnoreCase(fileType)) {
            throw new BaseException(StrUtil.format("暂不支持{}格式上传", fileType));
        }
        // 初始化
        BaseUtils.init(BeanUtil.toBean(ossConfig, UploadConfig.class));
        // 上传
        UploadFileVo fileVo =  OssUtils.uploadFile(file);
        return fileVo;
    }

    @Override
    public UploadFileVo uploadFile(MultipartFile file, Long toUserId) {
        String fileType = FileNameUtil.extName(file.getOriginalFilename());
        if ("webp".equalsIgnoreCase(fileType)) {
            throw new BaseException(StrUtil.format("暂不支持{}格式上传", fileType));
        }
        try {
            Long userId = ShiroUtils.getUserId();
            String question = null;
            if (toUserId.equals(Long.valueOf(10001))) {
                question = redisUtils.get(userId+":"+toUserId);
                if (null==question||"".equals(question)) {
                    throw new BaseException("作文问题需要先提问再上传作文参考图");
                }
            }
            // 初始化
            BaseUtils.init(BeanUtil.toBean(ossConfig, UploadConfig.class));
            // 上传
            UploadFileVo fileVo =  OssUtils.uploadFile(file);
            if (toUserId.equals(Long.valueOf(10001))) {
                String fileBase64 = Base64Util.getInstance().encode(file.getBytes());
                String oldImgurl = redisUtils.get(userId + "imgurl");
                log.info("oldImgurl:"+oldImgurl);
                String newImgurl = "";
                if (null==oldImgurl||"".equals(oldImgurl)) {
                    newImgurl = fileVo.getFullPath();
                }else {
                    newImgurl = oldImgurl+"#"+fileVo.getFullPath();
                }
                log.info("newImgurl:"+newImgurl);
                String content = ParseContent.OCR(fileBase64, PlatformConfig.ROOT_PATH, question, newImgurl);
                question = question+"#"+content;
                redisUtils.delete(userId + "replyimg");
                redisUtils.delete(userId + "img");
                redisUtils.delete(userId + "imgurl");
                redisUtils.delete(userId+":10001");
                redisUtils.set(userId + "replyimg", content, AppConstants.REDIS_MP_WEATHER_TIME, TimeUnit.MINUTES);
                redisUtils.set(userId + "img", "y", AppConstants.REDIS_MP_WEATHER_TIME, TimeUnit.MINUTES);
                redisUtils.set(userId + "imgurl", newImgurl, AppConstants.REDIS_MSG_TIME, TimeUnit.MINUTES);
                redisUtils.set(userId+":10001", question, AppConstants.REDIS_MP_WEATHER_TIME, TimeUnit.MINUTES);
            }else if (toUserId.equals(Long.valueOf(10002))) {
                String fileBase64 = Base64Util.getInstance().encode(file.getBytes());
                String content = ParseContent.OCR(fileBase64, PlatformConfig.ROOT_PATH, "", fileVo.getFullPath());
                redisUtils.set(fileVo.getFullPath(), content, AppConstants.REDIS_MP_WEATHER_TIME, TimeUnit.SECONDS);
            }
            return fileVo;
        }catch (IOException e) {}
        return null;
    }

    @Override
    public UploadVideoVo uploadVideo(MultipartFile videoFile) {
        // 初始化
        BaseUtils.init(BeanUtil.toBean(ossConfig, UploadConfig.class));
        // 上传视频文件
        UploadFileVo videoFileVo = OssUtils.uploadFile(videoFile);
        return BeanUtil.toBean(videoFileVo, UploadVideoVo.class)
                .setScreenShot(videoFileVo.getFullPath() + AppConstants.VIDEO_PARAM);
    }

    @Override
    public UploadAudioVo uploadAudio(MultipartFile audioFile) {
        // 初始化
        BaseUtils.init(BeanUtil.toBean(ossConfig, UploadConfig.class));
        // 上传音频文件
        UploadFileVo audioFileVo = OssUtils.uploadFile(audioFile);
        String data;
        try {
            data = Base64.encode(audioFile.getInputStream());
        } catch (IOException e) {
            throw new BaseException("语音识别接口调用异常，请稍后再试");
        }
        return BeanUtil.toBean(audioFileVo, UploadAudioVo.class).setSourceText(TencentUtils.audio2Text(tencentConfig, data));
    }

}
